//
//  ViewController.m
//  SCGraphView
//
//  Created by Anton Domashnev on 25.02.13.
//  Copyright (c) 2013 Anton Domashnev. All rights reserved.
//

#import "ViewController.h"
#import "GraphDataObject.h"
#import "GraphView.h"
#import "MBProgressHUD.h"

#import "PublicMethodEngine.h"

static ASIHTTPConnection *getData_connect;

@interface ViewController ()<GraphViewDelegate>{
    
    GraphView *graphView;
    GraphView *graphView2;
    GraphView *graphView3;
    MBProgressHUD *hud;
    
    int dataType;
    
}

@property (nonatomic, retain) GraphView *graphView;
@property (nonatomic, retain) GraphView *graphView2;
@property (nonatomic, retain) GraphView *graphView3;
@property (nonatomic, retain) MBProgressHUD *hud;

@end

@implementation ViewController

@synthesize graphView;
@synthesize graphView2;
@synthesize graphView3;
@synthesize hud;


- (id)initWithData:(NSArray *)array{
    
    self =[ super init];
    if (self) {
     
        dataArray = [[NSArray alloc]initWithArray:array];
    }
    return self;
    
}

- (id)initWithDataType:(int)type{
    
    self = [super init];
    if (self) {
        dataType = type;
    }
    return self;
    
}

- (void)dealloc{
    
    if (getData_connect != nil) {
        getData_connect.connectionDelegate = nil;
        [getData_connect release];
        getData_connect = nil;
    }
    
    [dataArray release];
    
    [graphView release];
    [hud release];
    
    [graphView2 release];
    [graphView3 release];
    
    [myScrollView release];
       
    [super dealloc];
}


- (NSInteger)randomBetweenFirst:(int)start andSecond:(int)end{
    
    return arc4random_uniform(end - start) + start;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.title = NSLocalizedString(@"图表", @"");
    
  	[myScrollView setContentSize:CGSizeMake(myScrollView.frame.size.width, 1000)];
    
//    [self addGraphView];
//    [self addGraphView2];
//    [self addGraphView3];
  
    [self loadData];
    
}

- (void)loadData{
    
    NSString *uid = [[NSUserDefaults standardUserDefaults] valueForKey:USER_ID];
    
    NSString *urlString = nil;
    
    switch (dataType) {
        case 1:
            urlString = [NSString stringWithFormat:@"%@/MobileHealth/WeightAction.aspx?UserID=%@",BASEURL,uid];
            break;
       case 2:
            urlString = [NSString stringWithFormat:@"%@/MobileHealth/UriaProteinAction.aspx?UserID=%@",BASEURL,uid];
            break;
        case 3:
            urlString = [NSString stringWithFormat:@"%@/MobileHealth/BloodSugarAction.aspx?UserID=%@",BASEURL,uid];
            break;
       case 4:
            urlString = [NSString stringWithFormat:@"%@/MobileHealth/BloodPressureAction.aspx?UserID=%@",BASEURL,uid];
            break;
       
        default:
            break;
    }
    
    
    
    
    
    
	NSURL *url = [NSURL URLWithString:urlString];
    
    
    if (getData_connect != nil) {
        getData_connect.connectionDelegate = nil;
        [getData_connect release];
        getData_connect = nil;
    }
    
    getData_connect = [[ASIHTTPConnection alloc] initGETWithURL:url resultDict:YES isCache:YES];
    getData_connect.connectionDelegate = self;
    
    [getData_connect startAsynchronous];
    

    [LoadingView showDefaultLoadingView];
}


#pragma mark connection delegate
- (void)requestFinished:(ASIHTTPConnection *)connection resultDict:(NSDictionary *)dict URL:(NSURL *)url info:(NSDictionary *)info{
    [LoadingView hideWithAnimated:YES];
    
    CLog(@"data = %@",dict);
    if (dict) {
        NSArray *array = [dict objectForKey:@"datalist"];
        if (array != nil && array.count > 0) {
            
            if (dataArray == nil) {
                dataArray = [[NSMutableArray alloc]init];
            }
            else{
                [dataArray removeAllObjects];
            }
            [dataArray addObjectsFromArray:array];
            [self addGraphView2];
            
        }
    }
    
}

- (void)requestFailed:(ASIHTTPConnection *)connection error:(NSError *)error URL:(NSURL *)url info:(NSDictionary *)info{
    [LoadingView hideWithAnimated:YES];
    
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark GraphView

- (void)addGraphView{
    
    self.hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    self.hud.labelText = NSLocalizedString(@"Loading graph data...", @"");
    
    UILabel *titleLable = [[UILabel alloc]initWithFrame:CGRectMake(10, 10, 300, 30)];
    titleLable.backgroundColor = [UIColor clearColor];
    titleLable.textAlignment =UITextAlignmentCenter;
    titleLable.textColor = [UIColor blackColor];
    titleLable.font = [UIFont boldSystemFontOfSize:15];
    titleLable.text = @"体重趋势图";
    [myScrollView addSubview:titleLable];
    [titleLable release];
    
   
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        
        NSString *startTimeStr = [[dataArray objectAtIndex:7] objectForKey:@"DataUploadTime"];
        NSDate *startDate = [[PublicMethodEngine sharedPublicMethodEngine] NSStringDateToNSDate:startTimeStr];
        NSString *endTimeStr = [[dataArray objectAtIndex:dataArray.count-1] objectForKey:@"DataUploadTime"];
        NSDate *endDate  = [[PublicMethodEngine sharedPublicMethodEngine] NSStringDateToNSDate:endTimeStr];
        
        NSMutableArray *referenceObjects = [[NSMutableArray alloc] init];
        
        for(int i = 0; i < dataArray.count; i++){
            
            NSDictionary *dict = [dataArray objectAtIndex:i];
            
            NSMutableDictionary *object = [[NSMutableDictionary alloc]init];
            
            [object setValue:[[PublicMethodEngine sharedPublicMethodEngine] NSStringDateToNSDate:[dict objectForKey:@"DataUploadTime"]] forKey:@"time"];
            
              
            float weight = [[dict objectForKey:@"Weight"] floatValue];
            
            int value = (int)(weight*10);
         
            [object setValue:[NSNumber numberWithInt:value] forKey:@"value"];
            
            long long int interval = [[[PublicMethodEngine sharedPublicMethodEngine] NSStringDateToNSDate:[dict objectForKey:@"DataUploadTime"]] timeIntervalSince1970];
            
            [object setValue:[NSNumber numberWithLongLong:interval] forKey:@"interValTime"];
            
            [referenceObjects addObject: object];
            [object release];
        }

        
        NSSortDescriptor *_sorter  = [[NSSortDescriptor alloc] initWithKey:@"interValTime"
                                                                 ascending:YES];
        [referenceObjects sortUsingDescriptors:[NSArray arrayWithObjects:_sorter, nil]];
        
        NSArray *graphObjects = [NSArray arrayWithArray: [GraphDataObject randomGraphDataObjectsArray:5 startDate:startDate endDate:endDate dataArray:referenceObjects]];
        [referenceObjects release];
        
        dispatch_async(dispatch_get_main_queue(), ^{
            
            if([graphObjects count] > 0){
                
                self.graphView = [[GraphView alloc] initWithFrame:DEFAULT_GRAPH_VIEW_FRAME objectsArray:graphObjects startDate:startDate endDate:endDate delegate:self];
                
                [myScrollView insertSubview:self.graphView atIndex:10];
            }
        });
        
       
        
    });
    
          
}


/*
- (void)addGraphView{
    
    self.hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    self.hud.labelText = NSLocalizedString(@"Loading graph data...", @"");
    
    UILabel *titleLable = [[UILabel alloc]initWithFrame:CGRectMake(10, 10, 300, 30)];
    titleLable.backgroundColor = [UIColor clearColor];
    titleLable.textAlignment =UITextAlignmentCenter;
    titleLable.textColor = [UIColor blackColor];
    titleLable.font = [UIFont boldSystemFontOfSize:15];
    titleLable.text = @"体重趋势图";
    [myScrollView addSubview:titleLable];
    [titleLable release];
    
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        
        NSDate *startDate = [NSDate dateWithTimeIntervalSince1970: 1351036800];
        NSDate *endDate = [NSDate dateWithTimeIntervalSince1970: 1382096000];
        
        NSArray *graphObjects = [NSArray arrayWithArray: [GraphDataObject randomGraphDataObjectsArray:2000 startDate:startDate endDate:endDate]];
        
        
        dispatch_async(dispatch_get_main_queue(), ^{
            
            if([graphObjects count] > 0){
                
                self.graphView2 = [[GraphView alloc] initWithFrame:CGRectMake(5, 40, 310, 206) objectsArray:graphObjects startDate:startDate endDate:endDate delegate:self];
                
                [myScrollView insertSubview:self.graphView2 atIndex:10];
            }
        });
    });
}


 
 */
- (void)addGraphView2{
    
    self.hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    self.hud.labelText = NSLocalizedString(@"Loading graph data...", @"");
    
    UILabel *titleLable = [[UILabel alloc]initWithFrame:CGRectMake(10, 10, 300, 30)];
    titleLable.backgroundColor = [UIColor clearColor];
    titleLable.textAlignment =UITextAlignmentCenter;
    titleLable.textColor = [UIColor blackColor];
    titleLable.font = [UIFont boldSystemFontOfSize:15];
    titleLable.text = @"体重趋势图";
    [myScrollView addSubview:titleLable];
    [titleLable release];
    
    
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        
        NSString *startTimeStr = [[dataArray objectAtIndex:0] objectForKey:@"DataUploadTime"];
        NSDate *startDate = [[PublicMethodEngine sharedPublicMethodEngine] NSStringDateToNSDate:startTimeStr];
        NSString *endTimeStr = [[dataArray objectAtIndex:dataArray.count-1] objectForKey:@"DataUploadTime"];
        NSDate *endDate  = [[PublicMethodEngine sharedPublicMethodEngine] NSStringDateToNSDate:endTimeStr];
        
        NSMutableArray *referenceObjects = [[NSMutableArray alloc] init];
        
        for(int i = 0; i < dataArray.count; i++){
            
            NSDictionary *dict = [dataArray objectAtIndex:i];
            
            NSMutableDictionary *object = [[NSMutableDictionary alloc]init];
            
            [object setValue:[[PublicMethodEngine sharedPublicMethodEngine] NSStringDateToNSDate:[dict objectForKey:@"DataUploadTime"]] forKey:@"time"];
            
            
            float weight = [[dict objectForKey:@"Weight"] floatValue];
            
            int value = (int)weight;
            
            [object setValue:[NSNumber numberWithInt:value] forKey:@"value"];
            
            long long int interval = [[[PublicMethodEngine sharedPublicMethodEngine] NSStringDateToNSDate:[dict objectForKey:@"DataUploadTime"]] timeIntervalSince1970];
            
            [object setValue:[NSNumber numberWithLongLong:interval] forKey:@"interValTime"];
            
            [referenceObjects addObject: object];
            [object release];
        }
        
        
//        NSSortDescriptor *_sorter  = [[NSSortDescriptor alloc] initWithKey:@"interValTime"
//                                                                 ascending:YES];
//        [referenceObjects sortUsingDescriptors:[NSArray arrayWithObjects:_sorter, nil]];
        
        //定义y轴范围
        [[NSUserDefaults standardUserDefaults] setValue:[NSNumber numberWithInt:0] forKey:@"minY"];
        [[NSUserDefaults standardUserDefaults] setValue:[NSNumber numberWithInt:100] forKey:@"maxY"];
        [[NSUserDefaults standardUserDefaults] setValue:[NSNumber numberWithInt:10] forKey:@"interval_Y"];
        
        
        
        NSArray *graphObjects = [NSArray arrayWithArray: [GraphDataObject randomGraphDataObjectsArray:10 startDate:startDate endDate:endDate dataArray:referenceObjects]];
        [referenceObjects release];
        
        dispatch_async(dispatch_get_main_queue(), ^{
            
            if([graphObjects count] > 0){
                
                self.graphView = [[GraphView alloc] initWithFrame:DEFAULT_GRAPH_VIEW_FRAME objectsArray:graphObjects startDate:startDate endDate:endDate delegate:self];
                
                [myScrollView insertSubview:self.graphView atIndex:10];
            }   
        });
        
        
        
    });
    
    
}


- (void)addGraphView3{
    
    self.hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    self.hud.labelText = NSLocalizedString(@"Loading graph data...", @"");
    
    UILabel *titleLable = [[UILabel alloc]initWithFrame:CGRectMake(10, 510, 300, 30)];
    titleLable.backgroundColor = [UIColor clearColor];
    titleLable.textAlignment =UITextAlignmentCenter;
    titleLable.textColor = [UIColor blackColor];
    titleLable.font = [UIFont boldSystemFontOfSize:15];
    titleLable.text = @"尿蛋白趋势图";
    [myScrollView addSubview:titleLable];
    [titleLable release];
    
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        
        NSDate *startDate = [NSDate dateWithTimeIntervalSince1970: 1351036800];
        NSDate *endDate = [NSDate dateWithTimeIntervalSince1970: 1382096000];
        
        NSArray *graphObjects = [NSArray arrayWithArray: [GraphDataObject randomGraphDataObjectsArray:2000 startDate:startDate endDate:endDate]];
        
        dispatch_async(dispatch_get_main_queue(), ^{
            
            if([graphObjects count] > 0){
                
                self.graphView3 = [[GraphView alloc] initWithFrame:CGRectMake(5, 540, 310, 206) objectsArray:graphObjects startDate:startDate endDate:endDate delegate:self];
                
                [myScrollView insertSubview:self.graphView3 atIndex:10];
            }
        });
    });
}



#pragma mark GraphViewDelegate

- (void)graphViewDidUpdate:(GraphView *)view{
    
    [MBProgressHUD hideHUDForView:self.view animated:YES];
    
    self.hud = nil;
}

- (void)graphViewWillUpdate:(GraphView *)view{
    
    if(!self.hud){
        
        self.hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        self.hud.labelText = NSLocalizedString(@"Loading graph data...", @"");
    }
}


@end
